(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:ApplicationCtrl
     * @description
     * # ApplicationCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('ApplicationCtrl', ["ERP_CONFIG", "$scope", "$rootScope", "$state", "$translate", "USER_ROLES", "dataService", "cacheService", "$timeout", "helper", "sessionService", "dhfprinterService", "$interval", "$location", "$compile",
            function(ERP_CONFIG, $scope, $rootScope, $state, $translate, USER_ROLES, dataService, cacheService, $timeout, helper, sessionService, dhfprinterService, $interval, $location, $compile) {
                var currentWareHouseKey = "currentWareHouse";
                //初始化
                $scope.init = function() {
                    var store = sessionService.get('store');
                    if (store) {
                        $rootScope.store_id = store.id;
                    }
                    $scope.currentUser = null;
                    $scope.userRoles = USER_ROLES;
                    //初始化
                    if (!window.localStorage.lang) {
                        window.localStorage.lang = 'zh-cn';
                    }
                    if (!window.localStorage.timezone) {
                        window.localStorage.timezone = moment.tz.guess();
                    }
                    $scope.timezone = window.localStorage.timezone;

                    //语言设定
                    $scope.cur_lang = window.localStorage.lang;
                    $timeout(function() {
                        if (!$rootScope.currentUser) {
                            $rootScope.getUserInfo(true);
                        }
                    }, 1000);

                    $scope.qrimage1 = '/web/dhfshop/app/images/kf.jpg';
                    $scope.wximg = '/web/dhfshop/app/images/wxkf.gif';
                    $rootScope.$on('event:up-store-id', function() {
                        $scope.printstatus = cacheService.get($rootScope.store_id + "print");
                        if ($scope.printstatus || cacheService.get($rootScope.store_id + "print_type")) {
                            $rootScope.$broadcast("event:kq-print");
                        }
                    });


                    $rootScope.$on('event:printer-closed', function() {
                        $timeout(function() {
                            $scope.printstatus = 0;
                        }, 1000);
                        cacheService.set($rootScope.store_id + "print", 0);
                    });

                    $rootScope.$on('event:printer-opened', function() {
                        $timeout(function() {
                            $scope.printstatus = 1;
                        }, 1000);
                        cacheService.set($rootScope.store_id + "print", 1);
                    });
                }

                $scope.changeTimeZone = function(data) {
                    window.localStorage.timezone = data;
                }

                //开启打印
                $scope.print = function(ty) {

                    cacheService.set($rootScope.store_id + "print", ty);
                    cacheService.set($rootScope.store_id + "print_type", ty);
                    if (ty) {

                        // if ($location.protocol() == 'https') {
                        //     var urls = window.location.href;
                        //     urls = urls.replace("https", "http");
                        //     window.location = urls;
                        // }
                        $rootScope.$broadcast("event:kq-print");

                    } else {
                        $rootScope.$broadcast("event:gb-print");
                    }

                }

                $scope.downloadprint = function() {
                    $scope.loginWin = $.alert({
                        backdrop: "static",
                        keyboard: false,
                        // bgcolor: "rgb(0,0,0,0.9)",
                        title: '<span >打印客户端</span>',
                        body: '<div style="text-align: center;margin-top:50px"> <div>请安装打印客户端，不然不能进行打印操作！<br/><span><a href="https://img.dhfapp.com/static/uploads/dhf-printer-win32-x64.zip">下载</span></div> </div>',
                        okBtn: '{{"login"|translate}}',
                        closeBtn: true,
                        hasfoot: false,
                        transition: true,
                        width: 'small',
                        show: function(e) {

                            $compile($(e.currentTarget).contents())($scope);
                        },
                        okHide: function(e) {

                        },
                    });
                }

                //查询是否关注微信公众号
                $rootScope.getsubscribe = function() {
                    var user = sessionService.get("tokenUser");
                    // if (user.Role !== 4 && user.CompanyId == 1) {
                    if (user.Role !== 4) {
                        $scope.checking = true;
                        $scope.scene_id = '1100' + Math.floor(Math.random() * 1000000);
                        var data = {
                            "unionid": $rootScope.currentUser.unionid,
                        };
                        dataService.phpsubscribeGet(data).then(function(re) {
                            if (!re.is_subscribe) {
                                // $scope.is_subscribe = re.is_subscribe;
                                getgzhimg().then($scope.showGzh);
                            }
                        });
                    }
                }

                $scope.showGzh = function() {
                    $scope.loginWin = $.alert({
                        backdrop: "static",
                        keyboard: false,
                        bgcolor: "rgb(0,0,0,0.9)",
                        title: '<span ng-if="!isIsvLogin">{{"扫码关注"|translate}}</span>',
                        body: '<div style="text-align: center;"> <img ng-src="{{gzhimg}}" width="250" style="border: 2px solid;" /> <br /> <br /> <font style="font-size:30px;line-height:2em;">请关注公众号，实时接收客服消息</font> </div>',
                        okBtn: '{{"login"|translate}}',
                        closeBtn: true, //是否显示叉hao 
                        hasfoot: false,
                        transition: true,
                        width: 'normal',
                        height: '380px',
                        show: function(e) {
                            if ($scope.gzhimg) {
                                getMemberState();
                            }
                            $compile($(e.currentTarget).contents())($scope);
                        },
                        okHide: function(e) {
                            $scope.checking = false;
                        },
                        hide: function(e) {
                            //手动关闭 弹窗 
                            $scope.checking = false;
                            rmAlert();
                        },
                        shown: function(e) {
                            $timeout(function() {
                                $('.sui-modal-backdrop').addClass('op');
                            }, 2000);
                        }
                    });
                }

                //生成关注二维码
                function getgzhimg() {
                    var data = {
                        "expire_seconds": 604800,
                        "action_name": "QR_STR_SCENE",
                        "action_info": {
                            "scene": {
                                "scene_str": "dhfsubscribe"
                            }
                        }
                    };
                    return dataService.wxQrcodeGet(ERP_CONFIG.BackGzhId, data).then(function(redata) {
                        if (redata) {
                            return $scope.gzhimg = "data:image/png;base64," + redata;
                        }
                    });
                }

                function getMemberState() {
                    var data = {
                        "unionid": $rootScope.currentUser.unionid,
                    };
                    dataService.phpsubscribeGet(data).then(function(redata) {
                        if (redata.is_subscribe) {
                            rmAlert();
                        } else {
                            if ($scope.checking) {
                                $timeout(getMemberState, 1000);
                            }
                        }
                    });
                }
                //透明下载图片
                $rootScope.logoUrl = function(url) {
                    return ERP_CONFIG.eprUrl + "/public/imgproxy/get?url=" + encodeURIComponent(url);
                }

                //复制到剪切板回调
                $rootScope.onSuccess = function(e) {
                    helper.message("已复制到剪贴板");
                    e.clearSelection();
                };

                //回调 方法 保存全局的店铺
                $rootScope.getstore = function(store) {
                    if (store) {
                        // console.error("store", store);
                        //店铺主键
                        $rootScope.store_id = store.id;
                        $rootScope.s_partner_id = store.partner_id;
                        //店铺类型
                        $rootScope.industryCode = store.code;
                        $rootScope.is_main = store.is_main;
                        ///上次选择的店铺 保存到缓存
                        sessionService.put("store", store);
                    }

                    $rootScope.$broadcast("event:load-menu");
                    $rootScope.$broadcast("event:up-store-id");
                    // $state.go("main");
                }

                $rootScope.whiteListUser = function() {
                    //分销白名单
                    var fxWhiteList = ERP_CONFIG.fxWhiteList;
                    var partner_id = sessionService.get("tokenUser").CompanyId;
                    if (partner_id) {
                        if (fxWhiteList.indexOf(partner_id) > -1) {
                            $rootScope.inWhiteList = true;
                        } else {
                            $rootScope.inWhiteList = false;
                        }
                    }
                    //全部开启
                    $rootScope.inWhiteList = true;
                }

                //*-------------------------------------------
                //** 全局侦听事件
                //-------------------------------------------*/

                $rootScope.$on('event:login-dialog-init-done', function() {
                    loadingToggle(true);
                });

                //登陆后获取用户信息
                $scope.$on('event:auth-loginConfirmed', function() {
                    // console.log("auth-loginConfirmed getUserInfo....")
                    // $rootScope.store_id = null;
                    $rootScope.getUserInfo();
                    $rootScope.whiteListUser();

                    // $timeout(function() {
                    //     $scope.kfQrCode(true);
                    // }, 2000);
                });

                //*-------------------------------------------
                // ** 全局rootScope定义 start
                // -------------------------------------------*/

                $rootScope.getUserInfo = function(getCache) {
                    return dataService.userCurrentGet(getCache).then(function(user) {
                        // console.log("getUserInfo：", user);
                        if (user) {
                            $rootScope.currentUser = $scope.currentUser = user || null;
                        }
                        // if (!ERP_CONFIG.debug) {
                        // $scope.getsubscribe();
                        $rootScope.getsubscribe();
                        // }
                        //通知加载菜单
                        $rootScope.$broadcast("event:load-menu");
                        dataService.getAllCity(function() {});
                    });
                }

                $rootScope.login = function() {
                    $rootScope.$broadcast('event:auth-loginRequired');
                }

                //重新登录
                $rootScope.relogin = function() {
                    $scope.currentUser = null;
                    $rootScope.login();
                }

                //注销登录
                $rootScope.logout = function() {
                    dataService.logout().then(function() {
                        $scope.currentUser = null;
                        $state.go("main");
                        helper.myAlert("success", null, 3, function() {
                            $rootScope.login();
                        });
                    });
                }

                //清空缓存
                $rootScope.removeAllCache = function($event) {
                    dataService.removeDataCache();
                    // location.reload();
                    // console.error("情况缓存设置timezone：", $scope.timezone);
                    window.localStorage.timezone = $scope.timezone;

                    helper.myTip("success", $event.currentTarget, null, null, null, "bottom");
                }

                //是否debug状态
                $rootScope.debug = function() {
                    return ERP_CONFIG.debug ? true : false;
                }

                //资源权限
                $rootScope.haveRight = function(api, field, value) {
                    if (!$rootScope.currentUser) {
                        return false;
                    }
                    if ($rootScope.currentUser.admin) {
                        return true;
                    }
                    var r = sessionService.get("roleResources");
                    var apiAlias = {
                        stockGet: "/rest/stock/get",
                    }

                    // console.log("------",r);
                    var apiIdentify = apiAlias[api] || api;
                    // console.log("----",api,r[apiIdentify]);
                    if (!r || !r[apiIdentify]) {
                        return false;
                    } else if (!field && !value) {
                        return r[apiIdentify] ? true : false;
                    } else if (field && !value) {
                        return r[apiIdentify].fields.indexOf(field) != -1 ? true : false;
                    } else if (!field && value) {
                        return r[apiIdentify].values.indexOf(value) != -1 ? true : false;
                    } else {
                        return r[apiIdentify].fields.indexOf(field) != -1 && r[apiIdentify].values.indexOf(value) != -1 ? true : false;
                    }
                }

                //获取体验二维码
                $scope.kfQrCode = function(usecache) {

                    // console.error("$scope", $rootScope.currentUser.open_id);
                    var questKey = "kfQrCode_" + $rootScope.currentUser.open_id;
                    var ttl = 24 * 3600;
                    var cacheVal = cacheService.get(questKey, ttl);
                    if (usecache && cacheVal) {
                        // console.log("缓存：24小时在弹出", questKey);
                    } else {
                        cacheService.set(questKey, 1, ttl);
                        var qrcodeWin = $.alert({
                            backdrop: "static",
                            keyboard: false,
                            title: '{{"技术支持"|translate}}',
                            body: '<p style="text-align:center"><img ng-src="{{qrimage1}}" width="240" /><h4 style="text-align:center;color:green;">微信扫码加我，随时在线技术支持</h4></p>',
                            okBtn: '{{"关闭"|translate}}',
                            closeBtn: true,
                            hasfoot: false,
                            transition: true,
                            width: 'small',
                            show: function(e) {
                                $compile($(e.currentTarget).contents())($scope);
                            },
                            okHide: function(e) {},
                            shown: function(e) {}
                        });
                        // console.log("没有查到缓存：", cacheService.get(questKey, ttl));
                    }
                }

                //菜单
                $rootScope.haveMenu = function(id) {
                    var rootMenus = sessionService.get("userMenus");

                    var result = false;
                    _.map(rootMenus, function(a) {
                        if (a.id == id) {
                            result = true;
                        }
                        if (a.sub && a.sub.length > 0) {
                            _.map(a.sub, function(b) {
                                if (b.id == id) {
                                    result = true;
                                }
                            });
                        }
                    });
                    return result;
                }


                //*-------------------------------------------
                // ** 全局rootScope定义 end
                // -------------------------------------------*/

                //更换语言
                $scope.switchLan = function(lang) {
                    $translate.use(lang);
                    window.localStorage.lang = lang;
                }
            }
        ]);
})();